package com.leetcode.LC;

import java.util.HashMap;
import java.util.Map;

public class LC1160 {//由于没有认真审题，产生偏差
    int sum = 0;
    public int countCharacters(String[] words, String chars) {
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < chars.length(); i++) {
            if (map.containsKey(chars.charAt(i))) {
                map.put(chars.charAt(i), map.get(chars.charAt(i)) + 1);
            } else {
                map.put(chars.charAt(i), 1);
            }
        }
        //用map存储chars，用
        Map<Character, Integer> map1 = new HashMap<>();
        map1.putAll(map);
        for (String word : words) {
            map1 = findWord(word, map1);
        }

        return sum;
    }

    public Map<Character, Integer> findWord(String word, Map<Character, Integer> map) {//如果成功则返回原改变后的map，不成功返回原map
        Map<Character, Integer> map1 = new HashMap<>();
        map1.putAll(map);
        for (int i = 0; i < word.length(); i++) {
            if (map.containsKey(word.charAt(i))) {
                map.put(word.charAt(i), map.get(word.charAt(i)) - 1);
                if (map.get(word.charAt(i)) < 0) {
                    return map1;
                }
            } else {
                return map1;
            }
        }

        System.out.println(word);
        sum += word.length();
        return map;
    }

    public static void main(String[] args) {//Map是浅复制
        /*Map<Character, Integer> map = new HashMap<>();
        map.put('a', 2);
        Map<Character, Integer> map1 = new HashMap<>();
        map1.putAll(map);
        map.remove('a');
        System.out.println(map1.get('a'));*/

        System.out.println(new LC1160().countCharacters(new String[]{"cat", "bt", "hat", "tree"}, "atach"));
    }

}
